package icu.makka.yygh.service.impl;

import com.alibaba.fastjson.JSONObject;
import icu.makka.yygh.model.hosp.Department;
import icu.makka.yygh.repository.DepartmentRepository;
import icu.makka.yygh.service.DepartmentService;
import icu.makka.yygh.vo.hosp.DepartmentQueryVo;
import icu.makka.yygh.vo.hosp.DepartmentVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
public class DepartmentServiceImpl implements DepartmentService {

    @Autowired
    private DepartmentRepository departmentRepository;

    /**
     * 删除科室接口
     * @param hoscode
     * @param depcode
     */
    @Override
    public void removeDepartment(String hoscode, String depcode) {
        log.info("业务层，删除科室接口...");
        departmentRepository.deleteByHoscodeAndDepcode(hoscode, depcode);
    }

    /**
     * 查询医院所有科室列表
     * @param hoscode
     * @return
     */
    @Override
    public List<DepartmentVo> findDeptTree(String hoscode) {
        log.info("业务层，查询医院所有科室列表，hoscode={}", hoscode);

        //创建list集合，用于最终数据封装
        List<DepartmentVo> result = new ArrayList<>();

        //根据医院编号，查询医院所有科室信息
        Department departmentQuery = new Department();
        departmentQuery.setHoscode(hoscode);
        Example example = Example.of(departmentQuery);
        //所有科室列表 departmentList
        List<Department> departmentList = departmentRepository.findAll(example);

        //根据大科室编号  bigcode 分组，获取每个大科室里面下级子科室
        Map<String, List<Department>> deparmentMap =
                departmentList.stream().collect(Collectors.groupingBy(Department::getBigcode));
        //遍历map集合 deparmentMap
        for(Map.Entry<String,List<Department>> entry : deparmentMap.entrySet()) {
            //大科室编号
            String bigcode = entry.getKey();
            //大科室编号对应的全局数据
            List<Department> deparment1List = entry.getValue();
            //封装大科室
            DepartmentVo departmentVo1 = new DepartmentVo();
            departmentVo1.setDepcode(bigcode);
            departmentVo1.setDepname(deparment1List.get(0).getBigname());

            //封装小科室
            List<DepartmentVo> children = new ArrayList<>();
            for(Department department: deparment1List) {
                DepartmentVo departmentVo2 =  new DepartmentVo();
                departmentVo2.setDepcode(department.getDepcode());
                departmentVo2.setDepname(department.getDepname());
                //封装到list集合
                children.add(departmentVo2);
            }
            //把小科室list集合放到大科室children里面
            departmentVo1.setChildren(children);
            //放到最终result里面
            result.add(departmentVo1);
        }
        //返回
        return result;
    }

    /**
     * 根据医院编号和科室编号获取科室信息
     * @param hoscode
     * @param depcode
     * @return
     */
    @Override
    public Department getDepartmentByHosCodeAndDepcode(String hoscode, String depcode) {
        log.info("业务层，根据医院编号和科室编号获取科室信息");
        Department department = departmentRepository.getDepartmentByHoscodeAndDepcode(hoscode, depcode);
        return department;
    }

    /**
     * 根据医院编号和科室编号获取科室名称
     * @param hoscode
     * @param depcode
     * @return
     */
    @Override
    public String getDepNameByHoscodeAndDepcode(String hoscode, String depcode) {
        log.info("业务层，根据医院编号获取科室名称");
        Department department = departmentRepository.getDepartmentByHoscodeAndDepcode(hoscode, depcode);
        return department.getDepname();
    }


    /**
     * 查询科室接口
     * @param page
     * @param limit
     * @param departmentQueryVo
     * @return
     */
    @Override
    public Page<Department> page(Integer page, Integer limit, DepartmentQueryVo departmentQueryVo) {
        log.info("科室分页，page={}，limit={}", page, limit);

        Department department = new Department();
        BeanUtils.copyProperties(departmentQueryVo, department);
        Pageable pageable = PageRequest.of(page - 1, limit);
        ExampleMatcher exampleMatcher = ExampleMatcher.matching()
                .withStringMatcher(ExampleMatcher.StringMatcher.EXACT)
                .withIgnoreCase(true);
        Example<Department> example = Example.of(department, exampleMatcher);
        Page<Department> pageInfo = departmentRepository.findAll(example, pageable);

        return pageInfo;
    }

    /**
     * 上传科室接口
     * @param paramMap
     */
    @Override
    public void saveDepartment(Map<String, Object> paramMap) {
        log.info("业务层，上传科室接口...");

        //数据转化
        String jsonString = JSONObject.toJSONString(paramMap);
        Department department = JSONObject.parseObject(jsonString, Department.class);
        //根据 医院编码 和 科室编码 查询科室信息
        Department departmentExist = departmentRepository
                .getDepartmentByHoscodeAndDepcode(department.getHoscode(), department.getDepcode());
        //判断科室是否存在
        if (departmentExist != null) {
            //如果科室存在，则更新科室信息
            department.setUpdateTime(new Date());
            department.setCreateTime(departmentExist.getCreateTime());
            department.setIsDeleted(0);
            departmentRepository.save(department);
        } else {
            //如果科室不存在，则新增科室信息
            department.setUpdateTime(new Date());
            department.setCreateTime(new Date());
            department.setIsDeleted(0);
            departmentRepository.save(department);
        }
    }
}
